import {Injectable} from '@angular/core';
import {Observable, of as ObserveOf, throwError} from 'rxjs';
import * as moment from 'moment';

@Injectable()
export class DataReportService {
    constructor() {
    }

    /**
     * 转换数组为树形结构
     *
     * @param data
     * @param options
     * @returns
     */
    flat2Nested<T>(data: Array<T>, options: {
        idProperty?: string,
        pathProperty?: string,
        parentIdProperty?: string,
        sortProperty?: string,
        childrenProperty?: string,
        rootId: any,
        pathSeparator?: string,
        filterProperties?: Array<string>,
        filterValues?: Array<string>,
        depth?: number
    }): Observable<T> {
        const ops = {
            ...{
                idProperty: 'id',
                pathProperty: 'path',
                parentIdProperty: 'parentId',
                childrenProperty: 'children',
                pathSeparator: ',',
                depth: -1
            }, ...options
        };

        // 参数错误判断
        const error = '树转换错误(from UtilService.flat2Nested)：';
        if (data.length <= 0) {
            console.error(`数据不应为空: \n${error}`);
            return throwError(new Error(`数据不应为空: \n${error}`));
        }
        // 数据预处理
        let newData: Array<T> = JSON.parse(JSON.stringify(data));
        const rootItem = newData.filter(item => {
            return item[ops.idProperty] === ops.rootId;
        })[0];
        if (!rootItem) {
            console.error(`无法找到指定根节点: \n${error}`);
            return throwError(new Error(`无法找到指定根节点: \n${error}`));
        }
        const rootLevel = rootItem[ops.pathProperty].split(ops.pathSeparator).length;
        if (ops.depth > 0) {
            newData = newData.filter(item => {
                const level = item[ops.pathProperty].split(ops.pathSeparator).length;
                let res = level > rootLevel;
                if (ops.depth > 0) {
                    res = res || level <= rootLevel + ops.depth;
                }
                return res;
            });
        }
        // 构建树
        const result = rootItem;
        const temp = {};
        temp[ops.rootId] = rootItem;
        newData.sort((a, b) => {
            return a[ops.pathProperty].split(ops.pathSeparator).length - b[ops.pathProperty].split(ops.pathSeparator).length;
        });
        while (newData.length > 0) {
            const item = newData[0];
            const parentItem = temp[item[ops.parentIdProperty]];
            if (parentItem) {
                if (!parentItem.children) {
                    parentItem.children = [];
                }
                parentItem.children.push(item);
                temp[item[ops.idProperty]] = item;
            }
            newData.shift();
        }
        return ObserveOf(result);
    }

    /**
     * 根据传入日期判断灌溉类型(夏秋灌:4-9月底 冬灌:10-3月底)
     *
     * @param date
     */
    irrigateType(date): string {
        const month = moment(date).month();
        return month < 9 && month > 2 ? '1' : '2';
    }

    /**
     * 根据传入日期判断月度上报类型(月度:4.1-9.10 灌季年度:9.11-3.31)
     *
     * @param date
     */
    monthlyReportType(date): string {
        const year = moment(date).year();
        const monthlyStart = `${year}-03-31`;
        const monthlyEnd = `${year}-09-11`;
        return moment(date).isAfter(monthlyStart) && moment(date).isBefore(monthlyEnd) ? '1' : '2';
    }


    /**
     * 获取近n年 年份列表
     *
     * @param years
     */
    getLatestYearList(years: number = 5): Array<number | string> {
        const list = [];
        const date = new Date();
        const currYear = date.getFullYear();
        for (let i = 0; i < years; i++) {
            list.push(currYear - i);
        }
        return list;
    }
}
